/**
 * Project Name:ulewo-common
 * File Name:MessageSettingsServiceImpl.java
 * Package Name:com.ulewo.service.impl
 * Date:2016年3月19日下午6:13:03
 * Copyright (c) 2016, ulewo.com All Rights Reserved.
 */

package com.ulewo.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ulewo.exception.BusinessException;
import com.ulewo.mapper.MessageSettingsMapper;
import com.ulewo.po.enums.EmailMessageType;
import com.ulewo.po.model.MessageSettings;
import com.ulewo.po.query.MessageSettingsQuery;
import com.ulewo.service.MessageSettingsService;
import com.ulewo.utils.StringTools;

/**
 * ClassName:MessageSettingsServiceImpl <br/>
 * Date:     2016年3月19日 下午6:13:03 <br/>
 * @author 多多洛
 * Copyright (c) 2016, ulewo.com All Rights Reserved. 
 */
@Service("messageSettingsService")
public class MessageSettingsServiceImpl implements MessageSettingsService {

    @Resource
    private MessageSettingsMapper<MessageSettings, MessageSettingsQuery> messageSettingsMapper;

    @Override
    public MessageSettings getMessageSettingsByUserId(Integer userId) {
        MessageSettingsQuery settings = new MessageSettingsQuery();
        settings.setUserId(userId);
        List<MessageSettings> list = messageSettingsMapper.selectList(settings);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void insert(MessageSettings settings) throws BusinessException {
        if (!StringTools.checkEmail(settings.getEmail())) {
            throw new BusinessException("请求参数错误");
        }
        settings.setMsgType(EmailMessageType.RECEIVE.getType());
        settings.setNoticeSignInType(EmailMessageType.NOTRECEIVE.getType());
        messageSettingsMapper.insert(settings);
    }

    @Override
    public void saveSettings(MessageSettings settings) throws BusinessException {
        EmailMessageType type = EmailMessageType.getEmailMessageType(settings.getMsgType());
        if (null == type || null == EmailMessageType.getEmailMessageType(settings.getNoticeSignInType())) {
            throw new BusinessException("请求参数错误");
        }
        MessageSettings setting = this.getMessageSettingsByUserId(settings.getUserId());
        if (setting == null) {
            throw new BusinessException("请先绑定邮箱");
        }
        settings.setEmail(setting.getEmail());
        messageSettingsMapper.insert(settings);
    }

    @Override
    public List<MessageSettings> selectList(MessageSettingsQuery query) {
        return messageSettingsMapper.selectList(query);
    }

}
